package com.example.demo.controller;

import com.example.demo.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.api.RedissonReactiveClient;
import org.redisson.api.RedissonRxClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("redis")
@Slf4j
public class RedissonController {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RedissonRxClient redissonRxClient;

    @Autowired
    private RedissonReactiveClient redissonReactiveClient;

    @Autowired
    private ReactiveRedisTemplate reactiveRedisTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisUtils redisUtils;


    @RequestMapping("/goods")
    public String getLock() {
        //getLock可以是订单号,秒杀里面是随机uuid,可以这么设置
        RLock lock = redissonClient.getLock("test1");
        try {
            lock.tryLock(3,10, TimeUnit.SECONDS);
            //锁住
            Integer test = Integer.parseInt(redisUtils.get("test"));
            if (test > 0) {
                test -= 1;
                log.info(test + "");
                redisUtils.set("test", test);
            } else return "error";
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return "ok";
    }


    @RequestMapping("addStock")
    public String add() {
        redisUtils.set("test", 50);
        return "ok";
    }
}
